import json
from django.views import View
from django.http import JsonResponse
from drf_spectacular.utils import extend_schema
from rest_framework.response import Response
from rest_framework.views import APIView

from app.models import User, MerchantInfo
from app.services.category_service import CategoryService
from middleware.util import AUTH_HEADER_PARAM


@extend_schema(
    tags=["商家菜品管理"],
    summary="商家创建菜品类别",
    description="商家可以创建一个新的菜品分类，需要 JWT Token 且角色为 merchant。",
    parameters=[AUTH_HEADER_PARAM],
    request={
        "application/json": {
            "example": {
                "category_name": "川菜",
                "sort_order": 100
            }
        }
    },
    responses={
        200: {
            "description": "成功创建类别",
            "type": "object",
            "example": {
                "code": 200,
                "message": "success",
                "data": {
                    "category_id": "abcd1234-5678-90ef-ghij-klmnopqrstuv",
                    "category_name": "川菜"
                }
            }
        },
        400: {"description": "缺少必要参数或请求体错误"},
        403: {"description": "权限不足或用户不是合法商家"},
        500: {"description": "系统错误"}
    }
)
class CreateCategoryView(APIView):
    def post(self, request):
        """
        商家创建菜品类别接口
        需要登录且角色为 'merchant'
        """
        try:
            # 从请求中获取数据
            data = json.loads(request.body)
            category_name = data.get("category_name")
            sort_order = data.get("sort_order", 100)

            if not category_name:
                return Response({
                    "code": 400,
                    "message": "缺少必要参数：category_name"
                }, status=400)

            # 从 JWT 解析出 user_id 并查找商家信息
            user_id = request.user_id
            try:
                user = User.objects.get(id=user_id)
                merchant_info = MerchantInfo.objects.get(merchant_id=user_id)
            except (User.DoesNotExist, MerchantInfo.DoesNotExist):
                return Response({
                    "code": 403,
                    "message": "您不是合法的商家用户"
                }, status=403)

            # 调用服务层创建分类
            return CategoryService.create_category(
                merchant_id=merchant_info.merchant_id,
                category_name=category_name,
                sort_order=sort_order
            )

        except json.JSONDecodeError:
            return Response({
                "code": 400,
                "message": "请求体格式错误"
            }, status=400)

        except Exception as e:
            return Response({
                "code": 500,
                "message": f"系统错误：{str(e)}"
            }, status=500)